package com.cetccloud.ap.proxy.channel.cossDomain.s30.channel.recv;

import com.cetccloud.ap.proxy.channel.cossDomain.s30.handler.recv.RecvChannelHandler;
import com.cetccloud.ap.proxy.channel.cossDomain.s30.handler.recv.RecvHandlerHolder;
import com.cetccloud.ap.proxy.channel.cossDomain.s30.handler.recv.file.FileXmlHandler;
import com.sun.jna.NativeLong;
import com.sun.jna.ptr.PointerByReference;
import com.thunisoft.exchange.gateway.protocol.GatewayProtocol;
import com.thunisoft.exchange.gateway.protocol.channel.GatewayChannelMessage;
import com.thunisoft.exchange.gateway.protocol.channel.GatewayChannelMessageType;
import com.thunisoft.exchange.gateway.protocol.file.GatewayFileMessage;
import com.thunisoft.exchange.gateway.protocol.file.xml.XmlDataUtils;
import com.wish.xsagent.JXSAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @ClassName Recv4SendHandle
 * @Description
 * @Author superz
 * @Date 2021/4/23 10:08
 * @Version 1.0
 **/
@Slf4j
@Component
public class Recv4RecvHandle implements JXSAgent.recv_func_ptr {

    @Autowired
    private RecvHandlerHolder recvHandlerHolder;

    @Override
    public void invoke(String msg, boolean result, PointerByReference data, NativeLong len) {
        log.info("### Recv4RecvHandle result: {}, msg: {} ", result, msg);
//        log.info("+++++++++++ callback data byte length := " + len);
//        new String(data.getPointer().getByteArray(0, len.intValue()), StandardCharsets.ISO_8859_1);

        boolean isFile = true;
        byte[] bytes = data.getPointer().getByteArray(0, len.intValue());
        try {
            XmlDataUtils.decode(bytes);
        } catch (Exception e) {
            isFile = false;
        }

        try {
            if (isFile) {
                GatewayFileMessage fileMessage = GatewayProtocol.decodeFileMessage(bytes);
                FileXmlHandler fileXmlHandler = recvHandlerHolder.getFileXmlHandler();
                fileXmlHandler.handle(fileMessage);
            } else {
                GatewayChannelMessage channelMessage = GatewayProtocol.decodeChannelMessage(bytes);
                GatewayChannelMessageType messageType = channelMessage.type();
                RecvChannelHandler handler = recvHandlerHolder.getChannelHandler(messageType);
                if (null == handler) {
                    log.error("Recv4RecvHandle 不支持的messageType: " + messageType);
                    return;
                }
                handler.handle(channelMessage);
            }
        } catch (Exception e) {
            log.error("Recv4RecvHandle invoke error", e);
        }

    }
}
